package com.itic.appbase.applications.login.controller;

import java.security.interfaces.RSAPrivateKey;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;

import com.itic.appbase.applications.login.service.LoginService;
import com.itic.appbase.applications.login.servlet.ValidateCodeServlet;
import com.itic.appbase.framework.common.basevo.User;
import com.itic.appbase.framework.common.constants.IticConst;
import com.itic.appbase.framework.common.constants.ResponseCode;
import com.itic.appbase.framework.common.controller.BaseController;
import com.itic.appbase.framework.exception.definition.SessionTimeoutException;
import com.itic.appbase.framework.utils.MD5Helper;
import com.itic.appbase.framework.utils.RSAHelper;
import com.itic.appbase.framework.utils.StringHelper;
import com.itic.appbase.framework.utils.configuration.PropertyHelper;

@Controller
@RequestMapping("/")
public class LoginController
        extends BaseController {

    private static final String USER_IS_USABLE = "1";

    @Autowired
    private LoginService        loginService;

    @RequestMapping(value = "login", method = RequestMethod.GET)
    public String loginGet(HttpServletRequest request) {
        // session判斷是否已經登錄
        if (StringHelper.isNotEmpty(this.findUserId(request))) {
            this.cleanUserSession(request);
        }
        return "login";
    }

    /**
     * 
     * @param request
     * @param response
     * @param model
     * @exception 空值
     *                ，系统
     */
    @SuppressWarnings("static-access")
    @RequestMapping(value = "login", method = RequestMethod.POST)
    @ResponseBody
    public Map<String, String> loginPost(HttpServletRequest request) {
        Map<String, String> resultMap = new HashMap<String, String>();
        String result = ResponseCode.UNKOWN_ERROR.getCode();
        // session冲突判断
        if (StringHelper.isNotEmpty(this.findUserId(request))) {
            this.cleanUserSession(request);
            this.cleanRSAKey(request);
        }
        // 登录参数获取
        String username = this.getCleanParams(request, IticConst.USERNAME);
        String password = this.getCleanParams(request, IticConst.PASSWORD);
        String portal = this.getCleanParams(request, IticConst.PORTAL); // 程序入口:系统、手机
        String captcha = this.getCleanParams(request, "captcha");

        if (StringHelper.isNotBlank(username) && StringHelper.isNotBlank(password)) {
            Boolean isCaptchaEnabled = Boolean.valueOf(PropertyHelper.getString("app.captcha.enabled"));
            Boolean codeValidate = new ValidateCodeServlet().validate(request, captcha);
            // 校验验证码
            if (!isCaptchaEnabled || codeValidate) {
                codeValidate = null;
                User incomeUser = new User(username, password, portal);
                User userInDb = loginService.confirmUser(incomeUser);
                // 无用户
                if (null == userInDb) {
                    result = ResponseCode.NO_USER.getCode();
                } else { // 唯一值
                    result = checkLogin(request, userInDb, incomeUser);
                }
            } else {
                result = ResponseCode.CAPTCHA_INVALID.getCode(); // 校验码错误
            }
        } else {
            result = ResponseCode.PARAM_INVALID.getCode(); // 参数错误
        }

        resultMap.put("result", result);
        return resultMap;
    }

    /**
     * 检测用户登录
     * 
     * @param request
     * @param userInDb 数据库查询用户
     * @param incomeUser 前台页面传递用户参数
     * @return
     */
    private String checkLogin(HttpServletRequest request, User userInDb, User incomeUser) {
        String result = "";
        // 无密码
        if (StringHelper.isBlank(userInDb.getPassword())) {
            result = "User Not Existed";
        } else {
            String isUsable = userInDb.getIsUsable();
            // 用户启用
            if (USER_IS_USABLE.equals(isUsable)) {
                String pwdDb = userInDb.getPassword();
                // 密码处理
                RSAPrivateKey privateKey = this.findRSAKey(request);
                String rsaPwd = RSAHelper.decryptByPrivateKeyJS(incomeUser.getPassword(), privateKey);
                String md5Pwd = MD5Helper.md5DoubleSalt(rsaPwd, incomeUser.getUsername());
                // 登录成功
                if (md5Pwd.equals(pwdDb)) {
                    result = ResponseCode.SUCCESS.getCode();
                    // 记录登录入口
                    userInDb.setPortal(incomeUser.getPortal());
                    // Session
                    this.setUserSession(request, userInDb);
                    this.cleanRSAKey(request);
                    incomeUser = null;
                } else {
                    result = ResponseCode.CREDENTIALS_INVALID.getCode();
                }
            } else {
                result = ResponseCode.USER_DISABLED.getCode();
            }

        }
        return result;
    }

    /**
     * 
     * @param request
     * @return
     * @throws
     */
    protected RSAPrivateKey findRSAKey(HttpServletRequest request) {
        Object obj = request.getSession().getAttribute(IticConst.PRIVATE_KEY);
        if (obj instanceof RSAPrivateKey) {
            return (RSAPrivateKey) obj;
        } else {
            throw new SessionTimeoutException("密匙验证失败，刷新页面");
        }
    }

    protected void cleanRSAKey(HttpServletRequest request) {
        request.getSession().removeAttribute(IticConst.PRIVATE_KEY);
    }
}